'use client'

import { useState, useEffect, useRef } from 'react'
import { Sheet, Cell, CellStyle, CollaborativeUser } from '@/types/sheet'
import { UniverProvider } from '@/components/univer/UniverProvider'
import { UniverSpreadsheet } from '@/components/sheet/UniverSpreadsheet'
import { useYjsCollaboration } from '@/hooks/useYjsCollaboration'
import { useAuth } from '@/contexts/AuthContext'

interface UnifiedSpreadsheetEditorProps {
  sheet: Sheet
  cells?: Cell[]
  onCellUpdate?: (row: number, column: number, value: string, formula?: string) => void
  onStyleUpdate?: (row: number, column: number, style: CellStyle) => void
  onSave?: (cells: Cell[]) => void
  onCursorUpdate?: (row: number, column: number, userId: string, userName: string) => void
  containerId?: string
  showCollaboration?: boolean
  allowEdit?: boolean
}

export const UnifiedSpreadsheetEditor: React.FC<UnifiedSpreadsheetEditorProps> = ({
  sheet,
  cells = [],
  onCellUpdate,
  onStyleUpdate,
  onSave,
  onCursorUpdate,
  containerId = 'univer-container',
  showCollaboration = true,
  allowEdit = true
}) => {
  const { user } = useAuth()
  const [isInitialized, setIsInitialized] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)

  // 协作功能
  const {
    collaborativeUsers,
    isConnected,
    cells: collaborativeCells,
    updateCell,
    updateCellStyle,
    updateCursor,
    loadInitialData
  } = useYjsCollaboration({
    sheetId: sheet?.id || '',
    userId: user?.id || 'anonymous',
    userName: user?.name || '匿名用户'
  })

  // 初始化数据
  useEffect(() => {
    if (sheet && cells.length > 0 && !isInitialized) {
      loadInitialData(cells)
      setIsInitialized(true)
    }
  }, [sheet, cells, isInitialized, loadInitialData])

  // 处理单元格更新
  const handleCellUpdate = (row: number, column: number, value: string, formula?: string) => {
    if (!allowEdit) {
      console.warn('Editing is not allowed')
      return
    }

    // 更新协作状态
    updateCell(row, column, value, formula)
    
    // 调用外部回调
    onCellUpdate?.(row, column, value, formula)
  }

  // 处理样式更新
  const handleStyleUpdate = (row: number, column: number, style: CellStyle) => {
    if (!allowEdit) {
      console.warn('Editing is not allowed')
      return
    }

    // 更新协作状态
    updateCellStyle(row, column, style)
    
    // 调用外部回调
    onStyleUpdate?.(row, column, style)
  }

  // 处理光标更新
  const handleCursorUpdate = (row: number, column: number) => {
    updateCursor(row, column)
    onCursorUpdate?.(row, column, user?.id || 'anonymous', user?.name || '匿名用户')
  }

  // 处理保存
  const handleSave = (cellsToSave: Cell[]) => {
    onSave?.(cellsToSave)
  }

  // 获取当前数据
  const getCurrentCells = () => {
    return collaborativeCells && collaborativeCells.length > 0 ? collaborativeCells : cells
  }

  if (!sheet) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <div className="text-center">
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            请选择一个表格
          </h3>
        </div>
      </div>
    )
  }

  return (
    <div ref={containerRef} className="flex-1 w-full h-full">
      <UniverProvider containerId={containerId} sheetId={sheet.id}>
        <UniverSpreadsheet
          sheet={sheet}
          cells={getCurrentCells()}
          onCellUpdate={handleCellUpdate}
          onStyleUpdate={handleStyleUpdate}
          onSave={handleSave}
          collaborativeUsers={showCollaboration ? collaborativeUsers : []}
          onCursorUpdate={handleCursorUpdate}
          allowEdit={allowEdit}
        />
      </UniverProvider>
    </div>
  )
}
